package com.fs.generator.ui.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Vector;

import lombok.extern.log4j.Log4j2;

@Log4j2
public class JDBConnect {

	private Connection connection;
	private Statement statement;

	public JDBConnect(String url, String driverName, String user, String passwd) {
		try {
			Class.forName(driverName);
			log.info("Opening db connection");
			connection = DriverManager.getConnection(url, user, passwd);
			statement = connection.createStatement();
		} catch (ClassNotFoundException ex) {
			log.error("Cannot find the database driver classes.{}", ex);
		} catch (SQLException ex) {
			log.error("Cannot connect to this database.{}", ex);
		}
	}

	public Vector executeQuery(String query) {
		if (connection == null || statement == null) {
			log.error("There is no database to execute the query.");
			return null;
		}
		try {
			ResultSet resultSet = statement.executeQuery(query);
			ResultSetMetaData metaData = resultSet.getMetaData();
			// Get all rows.
			Vector rows = new Vector();
			while (resultSet.next()) {
				Map<String, Object> newRow = new LinkedHashMap<String, Object>();
				for (int i = 1; i <= metaData.getColumnCount(); i++) {
					newRow.put(metaData.getColumnLabel(i).toLowerCase(), resultSet.getObject(i));
				}
				rows.addElement(newRow);
			}
			return rows;
			// close(); Need to copy the metaData, bug in jdbc:odbc driver.
		} catch (SQLException ex) {
			log.error("execute query fail.{}", ex);
		}
		return null;
	}

	public Connection getConnection() {
		return connection;
	}

	public Statement getStatement() {
		return statement;
	}

}
